package com.enterprise.support.utility;

import magick.*;

import java.awt.*;
import java.io.File;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2009-10-17
 * Time: 23:09:00
 * To change this template use File | Settings | File Templates.
 */
public class ImageMagick {
    static {
        System.setProperty("jmagick.systemclassloader", "no");
    }

    /**
     * 等比例缩放然后剪切
     *
     * @param inflie
     * @param outfile
     * @param width
     * @param height
     * @param xtemp
     * @param ytemp
     * @param mwidth
     * @param mheight
     */
    public synchronized static void resizeImg(String inflie, String outfile, int width, int height, int xtemp, int ytemp, int mwidth, int mheight) {
        try {
            ImageInfo info = new ImageInfo(inflie);
            MagickImage image = new MagickImage(info);
            Dimension dimension = image.getDimension();

            if (width > 0 || height > 0) {
                // 原图的大小
                int sw = (int) dimension.getWidth();
                int sh = (int) dimension.getHeight();
                if (sw > width || sh > height) {
                    image = resize(image, width, height);
                    dimension = image.getDimension();
                } else {
                    //如果原图像的大小 小于要缩放的图像大小，直接将要缩放的图像复制过去
                    //dimension.setSize();
                    mwidth = (mwidth != 0) ? mwidth : (int) dimension.getWidth();
                    mheight = (mheight != 0) ? mheight : (int) dimension.getHeight();
                    image = image.scaleImage(mwidth, mheight);
                    image.setFileName(outfile);
                    image.writeImage(info);
                    image.destroyImages();
                    return;
                }
            }

            // 缩放后的图像的宽和高
            int w = (int) dimension.getWidth();
            int h = (int) dimension.getHeight();

            // 如果缩放后的图像和要求的图像宽度一样，就对缩放的图像的高度进行截取
            if (w == width && height != 0) {
                // 计算X轴坐标
                int x = 0;
                int y = h / 2 - height / 2;
                image = image.cropImage(new Rectangle((xtemp != 0) ? xtemp : x, ytemp != 0 ? ytemp : y, width, height));
            } else if (h == height && width != 0) {
                // 否则如果是缩放后的图像的高度和要求的图像高度一样，就对缩放后的图像的宽度进行截取
                // 计算X轴坐标
                int x = w / 2 - width / 2;
                int y = 0;
                image = image.cropImage(new Rectangle((xtemp != 0) ? xtemp : x, ytemp != 0 ? ytemp : y, width, height));
            }

            /*如果是GIF图片 剪切后会存在空白背景, 先将图片保存为JPG格式 在move回GIF格式*/
            if (FileUtility.getPostfix(outfile).equalsIgnoreCase("GIF")) {
                image.setFileName(outfile.replaceAll("(?i)\\.GIF", ".JPG"));
            } else {
                image.setFileName(outfile);
            }
            image.writeImage(info);
            image.destroyImages();

            /*move回来*/
            if (FileUtility.getPostfix(outfile).equalsIgnoreCase("GIF")) {
                FileUtility.moveFile(new File(outfile.replaceAll("(?i)\\.GIF", ".JPG")), new File(outfile));
            }
        } catch (Exception ex) {
            ex.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    /**
     * 剪切上传头像图片
     *
     * @param inpath
     * @param outpath
     * @param x
     * @param y
     * @param zoom
     * @param nwidth
     * @param nheight
     * @throws Exception
     */
    public static void cropUploadifyHeaderImg(String inpath, String outpath, int x, int y, float zoom, int nwidth, int nheight) throws Exception {
        ImageInfo infile = new ImageInfo(inpath);
        MagickImage outfile = new MagickImage(new ImageInfo(inpath));
        zoom = zoom / 100;
        outfile = outfile.scaleImage((int) (outfile.getDimension().getWidth() * zoom), (int) (outfile.getDimension().getHeight() * zoom));
        outfile = outfile.cropImage(new Rectangle(x, y, nwidth, nheight));
        outfile.setFileName(outpath);
        outfile.writeImage(infile);
        outfile.destroyImages();
    }

    public static void cropImager(String inflie, String outfile, int top, int right, int bottom, int left) throws Exception {

        ImageInfo info = new ImageInfo(inflie);
        MagickImage image = new MagickImage(info);
        Dimension dimension = image.getDimension();
        if (top != 0) {
            image = image.cropImage(new Rectangle(0, top, (int) dimension.getWidth(), (int) dimension.getHeight() - top));
        }
        if (right != 0) {
            image = image.cropImage(new Rectangle(0, 0, (int) dimension.getWidth() - right, (int) dimension.getHeight()));
        }
        if (bottom != 0) {
            image = image.cropImage(new Rectangle(0, 0, (int) dimension.getWidth(), (int) dimension.getHeight() - bottom));
        }
        if (left != 0) {
            image = image.cropImage(new Rectangle(left, 0, (int) dimension.getWidth() - left, (int) dimension.getHeight()));
        }
        image.setFileName(null == outfile ? inflie : outfile);
        image.writeImage(info);
        image.destroyImages();
    }

    private static MagickImage resize(MagickImage source, Integer width, Integer height) throws Exception {
        double sx = width / source.getDimension().getWidth();
        double sy = height / source.getDimension().getHeight();
        if (sx < sy) {
            sx = sy;
            width = (int) (sx * source.getDimension().getWidth());
        } else {
            sy = sx;
            height = (int) (sy * source.getDimension().getHeight());
        }
        return source.scaleImage(width, height);
    }


    public static void mask(String logosrc, String targetfilepath) {
        try {
            ImageInfo info = new ImageInfo();
            MagickImage image = new MagickImage(new ImageInfo(targetfilepath));
            MagickImage mask = new MagickImage(new ImageInfo(logosrc));
            MagickImage target = new MagickImage(new ImageInfo(targetfilepath));
            if (image.getDimension().getWidth() > mask.getDimension().getWidth() + 20 && image.getDimension().getHeight() > mask.getDimension().getHeight() + 20) {
                image.setFileName(targetfilepath);
                image.writeImage(info);
                target.compositeImage(CompositeOperator.OverlayCompositeOp, mask, (int) (image.getDimension().getWidth() - (mask.getDimension().getWidth()) + 10), ((int) ((image.getDimension().getHeight() - (mask.getDimension().getHeight() + 10)))));
                target.setFileName(targetfilepath);
                target.writeImage(info);
            }
        } catch (MagickException e) {
            e.printStackTrace();
        }
    }

    /**
     * 水印(文字)
     */
    public static void maskfont(String targetfilepath) {
        try {
            ImageInfo info = new ImageInfo(targetfilepath);
            if (targetfilepath.toUpperCase().endsWith("JPG") || targetfilepath.toUpperCase().endsWith("JPEG")) {
                info.setCompression(CompressionType.JPEGCompression); //压缩类别为JPEG格式
                info.setPreviewType(PreviewType.JPEGPreview); //预览格式为JPEG格式
                info.setQuality(95);
            }
            MagickImage aImage = new MagickImage(info);
            if (aImage.getDimension().getWidth() > 330 && aImage.getDimension().getHeight() > 30) {
                DrawInfo aInfo = new DrawInfo(info);
                aInfo.setFill(PixelPacket.queryColorDatabase("white"));
                //aInfo.setUnderColor(new PixelPacket(0, 0, 0, 100));
                aInfo.setPointsize(14);
                //解决中文乱码问题,自己可以去随意定义个自己喜欢字体，我在这用的微软雅黑
                String fontPath = "C:/WINDOWS/Fonts/MSYH.TTF";
                //String fontPath = "/usr/maindata/MSYH.TTF";
                aInfo.setFont(fontPath);
                aInfo.setTextAntialias(true);
                aInfo.setOpacity(0);
                aInfo.setText("  www.srcsky.com 资源天空,领先的中文IT技术网站！ ");
                aInfo.setGeometry("+" + ((aImage.getDimension().getWidth() - 330) / 2) + "+" + (aImage.getDimension().getHeight() - 6));
                aImage.annotateImage(aInfo);
                aImage.setFileName(targetfilepath);
                aImage.writeImage(info);
                aImage.destroyImages();
            }
        } catch (MagickException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public static Dimension getDimension(String filepath) {
        try {
            ImageInfo info = new ImageInfo(filepath);
            MagickImage image = new MagickImage(info);
            Dimension dimension = image.getDimension();
            if (dimension.getWidth() < 1 || dimension.getHeight() < 1)
                return null;
            return dimension;
        } catch (Throwable ex) {
            return null;
        }
    }

    public static boolean isImage(String filepath) {
        return getDimension(filepath) != null;
    }

    public static void main(String[] args) throws Exception {
        cropImager("d:/255.JPG", "d:/255_back.JPG", 10, 10, 0, 0);
        //System.out.println("==============" + System.getProperty("java.library.path"));
        //System.setProperty("jmagick.systemclassloader ", "no");
        //ImageInfo infile = new ImageInfo("E:\\PROJECT\\MY\\www.gkfang.com\\webapps\\static\\fileuploader\\0\\0\\0\\4.JPG");

    }
}

